﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Diagnostics;
using System.Xml;
using hedefgrup.reports.renault.database;
using System.Collections;
using System.IO;
using hedefgrup.reports.common;
using hedefgrup.reports.renault.Services;

namespace update
{
    class Program
    {
        static readonly Program yyy = new Program();

        static void Main(string[] args)
        {

            for (int i = 0; i < 30; i++)
            {
                Console.WriteLine(Guid.NewGuid().ToString().ToLowerInvariant());
            }
            Console.ReadLine();
            return;
            OptInOutUpdate optInOutUpdate = new OptInOutUpdate();
            string yyyyMM = null;
            string mdb = null;
            int iid = 0;

            try
            {
                yyyyMM = args[0];
                mdb = args[1];
                iid = int.Parse(args[2]);
            }
            catch
            {
                Console.WriteLine("Usage: update 201412 mdbfile.mdb <IID (0 for all)>");
                return;
            }

            Console.WriteLine(optInOutUpdate.Execute(yyyyMM, mdb, iid, Path.Combine(Path.GetDirectoryName(mdb), Path.GetFileNameWithoutExtension(mdb) + ".xml")));

            // for (int i = 0; i < 4000; i++)
            //{
            //    string result = optInOutUpdate.Execute("201412", @"C:\Private\Coding\hedef-grup\OxWebCATI\surveyData\RD_ARALIK_RENAULT\surveyData - Copy.mdb", i);
            //    Console.WriteLine("ID: {0}, result: {1}", i, result);
            //}

            //ProcessUpdate("renault_2013_data", "S17_OUV1", 1, 49, 3000);
            //ProcessUpdate("renault_2013_data", "S18_OUV1", int.MinValue, int.MaxValue, 1000);
            //ProcessUpdate("renault_2013_data", "S18_OUV2", int.MinValue, int.MaxValue, 1000);

            //db.setConnectionString("Server=(local);Database=www.hedef-grup.com-NP;Integrated Security=SSPI;");

            //Tree tree = Tree.FromPath("/QVN2013/QUESTIONNAIRE/S17");
            //Console.WriteLine("Text: {0}", tree["Text", "*"]);
            //Console.WriteLine("Text: {0}", tree["Text", "*"]);
            //Tree parent = tree.Parent;

            //BuildTree();

            // FillParentsInData();

            //DumpTree();

            //TreeXPathParser parser = new TreeXPathParser("QVN2013/ORGANIZATION/TR/*/*/*(dealer)");

            //IEnumerable<Tree> trees = Tree.Root.Select("QVN2013/ORGANIZATION/TR/*(area)/*(coordinator)/*(dealer)/34431");

            //GenerateReport();
        }

        //private static void GenerateReport(Report_Abstract rp, string reportMonth)
        //{
        //    Console.WriteLine("Starting {0}", rp.GetType().Name + "_" + reportMonth);
        //    Stopwatch sw = Stopwatch.StartNew();
        //    rp.Context.ApplicationPath = @"C:\Private\Coding\hedef-grup\www.hedef-grup.com";

        //    Criteria cr = rp.GetCriteriaByName("Begin Month");
        //    cr.Values.Clear();
        //    cr.Values.Add(reportMonth);
        //    cr = rp.GetCriteriaByName("End Month");
        //    cr.Values.Clear();
        //    cr.Values.Add(reportMonth);

        //    // rp.GetFilterByName("MODELGRUP").Value = "Renault Binek";

        //    ReportResult results = rp.GenerateReport();
        //    Console.WriteLine("Report generated in {0} ms", sw.Elapsed.TotalMilliseconds);
        //    sw.Reset();
        //    sw.Start();
        //    File.WriteAllText(@"C:\temp\hedef-grup\reportDump\" + rp.GetType().Name + "_" + reportMonth + "_RENAULT_BINEK.txt", results.Dump());
        //    Console.WriteLine("Report dumped in {0} ms", sw.Elapsed.TotalMilliseconds);
        //}

        //private static void GenerateReport()
        //{
        //    DateTime now = DateTime.Now;

        //    for (int i = 9; i <= 9; i++)
        //    {
        //        string reportMonth = string.Format("{0:0000}{1:00}", 2013, i);
        //        //GenerateReport(new Report_Dealer_Renault_Dacia(), reportMonth);
        //        //GenerateReport(new Report_Make_Model(), reportMonth);
        //        //GenerateReport(new Report_Standard(), reportMonth);
        //        //GenerateReport(new Report_Not_Recommending_Reasons(), reportMonth);
        //        //GenerateReport(new Report_Verbatim(), reportMonth);
        //        //GenerateReport(new Report_AudioRecordings(), reportMonth);
        //        GenerateReport(new Report_DealerInterviewCounts(), reportMonth);

        //    }
        //    // Report_Abstract rp = new Report_Make_Model();
        //    // Report_Standard rp = new Report_Standard();
        //    // Report_Not_Recommending_Reasons rp = new Report_Not_Recommending_Reasons();
        //    // Report_Verbatim rp = new Report_Verbatim();
        //    // Report_AudioRecordings rp = new Report_AudioRecordings();


        //    // rp.GetFilterByName("MARKA").Value = "Dacia";
        //    // rp.Filters["KOORDINATOR"].Value = "1.1";

        //    Console.Write("Calculated in {0} ms", DateTime.Now.Subtract(now).Milliseconds);
        //    return;

        //    //string[] vals = new Criteria_Month().GetValueList();
        //    //string[] vals2 = new Filter_DataColumn() { ColumnName = "KOORDINATOR" }.GetValueList();
        //}

        private static void DumpTree()
        {
            Tree qvn2013 = Tree.Root;
            File.WriteAllText(@"C:\temp\treedump.txt", qvn2013.Dump());
        }

        static void BuildTree()
        {
            //db.execute("TRUNCATE TABLE Tree");
            //db.execute("TRUNCATE TABLE Attribute");

            db.execute("DELETE Attribute WHERE [UniqueId] IN (SELECT UniqueId FROM Tree WHERE [Path] LIKE '/SATIS_SUREC%')");
            db.execute("DELETE Tree WHERE [Path] LIKE '/SATIS_SUREC%'");

            XmlDocument doc = new XmlDocument();
            doc.Load(@"C:\Private\Coding\hedef-grup\www.hedef-grup.com\x\qvn2013dacia.xml");

            Tree root = Tree.Root;

            Tree qvn2013 = root.GetChild("QVN2013");
            //qvn2013["Text"] = "SATIŞ SÜREÇ";
            //qvn2013["Description"] = "SATIŞ SÜREÇ Araştırması";

            //Tree questionnaire = qvn2013.CreateChild("QUESTIONNAIRE", "questionnaire");
            //questionnaire["Text"] = "Questionnaire";
            //questionnaire["Description"] = "Satış Süreç Araştırması Soru Formu";

            //XmlNodeList questionNodes = doc.DocumentElement.SelectNodes("questionnaire/question");
            //foreach (XmlNode questionNode in questionNodes)
            //{
            //    Tree question = questionnaire.CreateChild(questionNode.Attributes["code"].Value, "question");
            //    question["Text"] = questionNode.Attributes["name"].Value;
            //    question["Description"] = questionNode.Attributes["name"].Value;

            //    XmlNodeList optionNodes = doc.DocumentElement.SelectNodes("questionnaire/question[@code='" + questionNode.Attributes["code"].Value + "']/option");
            //    foreach (XmlNode optionNode in optionNodes)
            //    {
            //        Tree option = question.CreateChild(optionNode.Attributes["value"].Value, "option");
            //        option["Text"] = optionNode.Attributes["text"].Value;
            //    }
            //}

            Tree organization = qvn2013.CreateChild("DACIA_ORGANIZATION", "organization");
            organization["Text"] = "Organization";
            organization["Description"] = "The QVN 2013 Project Dacia Dealership Organization";

            XmlNodeList dealerNodes = doc.DocumentElement.SelectNodes("organization/dealer");
            Hashtable registeredDealers = new Hashtable();

            foreach (XmlNode dealerNode in dealerNodes)
            {
                RegisterDealer(organization, dealerNode, registeredDealers, doc);
            }
        }

        static Tree RegisterDealer(Tree organization, XmlNode dealerNode, Hashtable registeredDealers, XmlDocument doc)
        {
            if (registeredDealers.ContainsKey(dealerNode.Attributes["code"].Value))
            {
                return registeredDealers[dealerNode.Attributes["code"].Value] as Tree;
            }

            string parentDealerCode = dealerNode.Attributes["parent"] != null ? dealerNode.Attributes["parent"].Value : null;
            Tree parentDealer = null;
            if (!string.IsNullOrEmpty(parentDealerCode))
            {
                if (registeredDealers.ContainsKey(parentDealerCode))
                {
                    parentDealer = registeredDealers[parentDealerCode] as Tree;
                }
                else
                {
                    XmlNode parentDealerNode = doc.DocumentElement.SelectSingleNode("organization/dealer[@code='" + parentDealerCode + "']");
                    Debug.Assert(parentDealerNode != null);
                    parentDealer = RegisterDealer(organization, parentDealerNode, registeredDealers, doc);
                }
            }
            else
            {
                parentDealer = organization;
            }

            Tree dealer = parentDealer.CreateChild(dealerNode.Attributes["code"].Value, dealerNode.Attributes["type"].Value);
            dealer["Text"] = dealerNode.Attributes["name"].Value;

            if (dealerNode.Attributes["monitor"] != null && dealerNode.Attributes["monitor"].Value == "true")
            {
                dealer["Flop", "*"] = "1";
            }
            if (dealerNode.Attributes["sort_prefix"] != null)
            {
                dealer["SortPrefix", "*"] = dealerNode.Attributes["sort_prefix"].Value;
            }
            if (dealerNode.Attributes["override_child_query"] != null)
            {
                dealer["ChildQuery", "*"] = dealerNode.Attributes["override_child_query"].Value;
            }

            registeredDealers.Add(dealerNode.Attributes["code"].Value, dealer);
            return dealer;
        }

        private static void FillParentsInData()
        {
            // Tree[] dealers = Tree.Root.Select("/QVN2013/ORGANIZATION/
        }

        //static void ProcessUpdate(string table, string column, int min, int max, int increase)
        //{
        //    SqlConnection conn = new SqlConnection("server=(local);user id=sa;password=Int%Sube;database=www.hedef-grup.com");
        //    conn.Open();

        //    SqlCommand comm = new SqlCommand();

        //    comm.CommandText = "SELECT DISTINCT " + column + " FROM " + table + " (NOLOCK)";
        //    comm.CommandType = System.Data.CommandType.Text;
        //    comm.Connection = conn;

        //    SqlDataAdapter adap = new SqlDataAdapter(comm);

        //    DataTable dtbl = new DataTable();
        //    adap.Fill(dtbl);

        //    conn.Dispose();
        //    comm.Dispose();

        //    foreach (DataRow row in dtbl.Rows)
        //    {
        //        string newValue = "";
        //        string oldValue = row[0].ToString().Trim();

        //        if (string.IsNullOrEmpty(oldValue))
        //        {
        //            continue;
        //        }

        //        string[] values = oldValue.Split(',');
        //        foreach (string valueString in values)
        //        {
        //            int value;
        //            if (!int.TryParse(valueString, out value))
        //            {
        //                Debugger.Break();
        //            }
        //            if (value >= min && value <= max)
        //            {
        //                value += increase;
        //            }
        //            newValue += value + ",";
        //        }
        //        newValue = newValue.TrimEnd(',');

        //        if (newValue != oldValue)
        //        {
        //            Console.WriteLine("UPDATE {0} SET {1} = '{2}' WHERE {1} = '{3}'", table, column, newValue, oldValue);
        //        }
        //    }
        //}
    }
}
